package com.session.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iman.common.util.ConfigUtil;
import com.iman.manjusri.Web7Constants;
import com.iman.manjusri.domain.SessionBean;
import com.iman.manjusri.service.SharedSessionService;
import com.iman.manjusri.util.HoldWebSpringContext;
import com.iman.manjusri.util.Web7Util;

public class SessionFilter implements Filter {
	private String encoding;
	private  Logger logger = LoggerFactory.getLogger(SessionFilter.class);

	public SessionFilter() {
	}

	public void init(FilterConfig filterconfig) throws ServletException {
		encoding = "utf-8";
	}

	public void doFilter(ServletRequest servletrequest, 	ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) servletrequest;
		//有些请求不需要sessionID
		Map<String,Boolean>  nofilters    = new HashMap<String,Boolean>(){{
			this.put("/register/chinacity", true);
		}}; 
		
		String  path = req.getRequestURI();
		
		if(nofilters.containsKey(path)){
			filterchain.doFilter(servletrequest, servletresponse);
			return;
		}
		
		HttpServletResponse resp = (HttpServletResponse) servletresponse;

		//获取所有的cookie
		Cookie[] cookies = req.getCookies();
		
		
		String teacherYN= ConfigUtil.getString( "session.test");
		String  uid ="";
		String  uidpk ="";
		  /*********滨哥** 教师*********/
		  if(teacherYN!=null && "true".equalsIgnoreCase(teacherYN.trim())){
			  
			  /***************其他人可以使用这个  学生******************/
			  //    uid = "269ec90926c0478c1e792c484b3d76a4";
			  //   uidpk = "68d95fd504d46ab4e0ecc3736e773a78";
			  
			  //学员
			    uid = "2cee4e45783ab872237939585870cf35";
			     uidpk = "e49c48ae3cbae47c0239edb156015d15";
		  }
		 
		 
			
		  
		if(cookies!=null)
		{
			for(Cookie c:cookies)
			{
				logger.info("cookie name="+c.getName()+"  cookie value:="+c.getValue()+"  all=:"+c.toString());
			
				if(Web7Constants.SHARECOOKIEUSERID .equals(c.getName() )){
					uid = c.getValue();
				}
				
				if(Web7Constants.SHARECOOKIEUSERID_PRIVATEKEY .equals(c.getName() )){
					uidpk = c.getValue();
				}
			}
		}
		
		//TODO	如果   false 说明 失效，或者 错误，需要重新登陆
	  	 boolean  isRightCookie =   Web7Util.checkCookieIdIsOk(uid,uidpk);
	  	 
	  	  
	  	 logger.info("cookie nameuid="+uid+"  cookie uidpk:="+uidpk +"-----------》isRightCookie  result =:"+isRightCookie );
		
		 SessionBean sessionBean = new   SessionBean();
		 
		 
		 if(isRightCookie){
			 HttpSession session = req.getSession();
			//  redis 中缓存的KEY SessionBean.USER_SESSION_KEY_PERFIX+sessionkey,  SessionBean.USER_SESSION_SUBKEY_SESSION
			 sessionBean = (SessionBean)session.getAttribute(SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION );
			
			 //当前容器不存在 ，
		     if(sessionBean == null ){
		    	//容器缓存失效
		    	try{
					SharedSessionService sessionUtil =	 	HoldWebSpringContext.getBean("shareusersession", SharedSessionService.class);
					sessionBean = sessionUtil.getSeesion(uid);
				}catch(Exception e){
				  logger.error(e.getMessage(),e);
				}
		     }
		 }
		
	
		
		//最后验证是否真的失效
	 	 
		if (sessionBean == null ) {
			//TODO	没有登陆  ，返回登陆页面，， 真的 失效了  ，那么重新登陆
			  
		  	 logger.error("重新登录" );
		
		}else{
			HttpSession session = req.getSession();
			//放入内部session 数据量
		    session.setAttribute(SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION ,sessionBean );
		    logger.info("放入本地session"+ SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION +"--->"+sessionBean);
		}

		
		
		filterchain.doFilter(servletrequest, servletresponse);
	}

	public void destroy() {

	}
}